package com.lottery.ruok.lottrey.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.TransferPayActivity;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.RechargeThirdRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.RechargeThirdResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import glideHelp.GlideHelper;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import ui.SquareImageView;
import utils.Utils;

/**
 * Created by ASUS on 2017/7/27.
 */

public class OtherRemittanceFragment extends BaseFragment implements TextWatcher{
    @BindView(R.id.qrcode)
    SquareImageView qrcode;
    @BindView(R.id.charge_now)
    TextView chargeNow;
    @BindView(R.id.refresh)
    TextView refresh;
    @BindView(R.id.money)
    EditText money;
    @BindView(R.id.certificate)
    EditText certificate;
    @BindView(R.id.submit)
    TextView submit;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.money_unit)
    View money_unit;

    private TransferPayActivity transferPayActivity;

    private int mIndex = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.transfer_other_lottery_fragment, container, false);

        ButterKnife.bind(this, view);

        init();
        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        transferPayActivity = (TransferPayActivity) activity;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        if(money.getText().length() > 0 && certificate.getText().length() > 0){
            submit.setTextColor(Color.parseColor("#ffffff"));
            submit.setEnabled(true);
        } else {
            submit.setTextColor(Color.parseColor("#9942F7"));
            submit.setEnabled(false);
        }
    }

    private void init() {
        certificate.addTextChangedListener(this);
        money.addTextChangedListener(this);

        if(transferPayActivity != null) {
            money.setText(transferPayActivity.getIntent().getStringExtra("money"));
            if(transferPayActivity.getRechargeBankResponses != null && transferPayActivity.getRechargeBankResponses.get(getArguments().getInt("index")) != null){
                title.setText(transferPayActivity.getRechargeBankResponses.get(getArguments().getInt("index")).getNames() + "交易订单后六位:");
                if(transferPayActivity.getRechargeBankResponses.get(getArguments().getInt("index")).getData() != null) {
                    GlideHelper.loadImageWithoutCache(getActivity(), transferPayActivity.getRechargeBankResponses.get(getArguments().getInt("index")).getData().get(mIndex).getQrcode(), qrcode);
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = 100)
    public void doSomething() {
//        Utils.saveImageLocal(getActivity(), transferPayActivity.getRechargeBankResponses.get(getArguments().getInt("index")).getData().get(mIndex).getQrcode());
//
//        Utils.showToast( "二维码图片已保存到本地相册中");

        View decorview = getActivity().getWindow().getDecorView();
        decorview.setDrawingCacheEnabled(true);
        Bitmap Bmp = decorview.getDrawingCache();
        MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), Bmp, System.currentTimeMillis() + "", System.currentTimeMillis() + "");
        Utils.showToast("截屏已保存到本地相册中");
    }

    @PermissionFail(requestCode = 100)
    public void doFailSomething() {
        Utils.showToast("截屏保存失败，请查看是否开启相册存储权限");
    }

    @OnClick({R.id.charge_now, R.id.refresh, R.id.submit, R.id.money_unit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.money_unit:
                money.requestFocus();
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
                money.setSelection(money.getText().length());
                break;

            case R.id.charge_now:
                //把当前图片存储到相册，要多种手机进行测试
                PermissionGen.with(this)
                        .addRequestCode(100)
                        .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .request();
                break;
            case R.id.refresh:
                if (mIndex + 1 == transferPayActivity.getRechargeBankResponses.get(getArguments().getInt("index")).getData().size()) {
                    mIndex = 0;
                } else {
                    mIndex++;
                }
                GlideHelper.loadImageWithoutCache(getActivity(), transferPayActivity.getRechargeBankResponses.get(getArguments().getInt("index")).getData().get(mIndex).getQrcode(), qrcode);
                break;
            case R.id.submit:
                if(getArguments().getInt("index") == 1){
                    //sendAnalyticMsg("lottery_" + ChargeActivity.ANALYTIC_VERSION + "_me_recharge_manual_alipay_submit");
                } else if(getArguments().getInt("index") == 2){
                    //sendAnalyticMsg("lottery_" + ChargeActivity.ANALYTIC_VERSION + "_me_recharge_manual_weichat_submit");
                } else if(getArguments().getInt("index") == 3){
                    //sendAnalyticMsg("lottery_" + ChargeActivity.ANALYTIC_VERSION + "_me_recharge_manual_cft_submit");
                }
                RetrofitBase.getRetrofit().create(RechargeThirdRequest.class)
                        .getResult(UserInfo.getToken(),
                                transferPayActivity.getRechargeBankResponses.get(getArguments().getInt("index")).getNames_alias(),
                                money.getText().toString(),
                                certificate.getText().toString(),
                                transferPayActivity.getRechargeBankResponses.get(getArguments().getInt("index")).getId(),
                                transferPayActivity.getRechargeBankResponses.get(getArguments().getInt("index")).getData().get(mIndex).getId(),
                                transferPayActivity.getRechargeBankResponses.get(getArguments().getInt("index")).getData().get(mIndex).getQrcode())
                        .compose(RxHelper.<RechargeThirdResponse>handleResult())
                        .subscribe(new RxSubscribe<RechargeThirdResponse>(getActivity()) {
                            @Override
                            protected void _onNext(RechargeThirdResponse rechargeThirdResponse) {
                                Utils.showToast(rechargeThirdResponse.getMsg());

                                getActivity().finish();
                            }

                            @Override
                            protected boolean showDialog() {
                                return true;
                            }
                        });
                break;
        }
    }
}
